from flask import request

from owl_ai.domain.chat_entity import ChatFileMessage
from owl_common.base.model import AjaxResponse
from owl_common.config import OWLConfig
from owl_common.descriptor.serializer import JsonSerializer
from owl_ai.service import ChatFilesService
from owl_common.utils import FileUploadUtil
from ... import reg


@reg.api.route("/ai/chat/file/upload", methods=["POST"])
@JsonSerializer()
def file_upload():
    chat_id = request.form.get('chat_id')
    message_id = request.form.get('message_id')
    files = request.files
    if files:
        file = files.get('file')
        resource_path = FileUploadUtil.upload(file, OWLConfig().upload_path)

        chat_file_message = ChatFileMessage()
        chat_file_message.chat_id = chat_id
        chat_file_message.message_id = message_id
        chat_file_message.name = file.filename
        chat_file_message.path = resource_path
        chat_file_message.suffix = file.filename.split('.')[-1]

        file_id = ChatFilesService.upload_file(chat_file_message)

        ajax_response = AjaxResponse.from_success()
        setattr(ajax_response, "msg", "上传成功")
        setattr(ajax_response, "data", {
            "id": file_id
        })
        return ajax_response
    else:
        ajax_response = AjaxResponse.from_error()
        setattr(ajax_response, "msg", "文件不能为空")
        return ajax_response
